<template>

  <div v-if="personList.length > 0">
    <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息</el-divider>
    <el-table :data="personList" border>
      <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
      <el-table-column label="参与人" align="center" width="200" prop="participanName" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
      <el-table-column label="结束日期" align="center" prop="endDate" />
      <el-table-column label="备注" align="center" width="120" prop="remark" />
      <el-table-column label="操作员" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div v-if="attachmentList.length > 0">
    <el-divider style="font-size: 16px; font-weight: bold;">附件信息</el-divider>
    <el-table :data="attachmentList" border>
      <el-table-column label="标签页" align="center" prop="phaseName" />
      <el-table-column label="附件类别" align="center" prop="attachmentType">
        <template #default="scope">
          <dict-tag :options="file_type" :value="scope.row.attachmentType" />
        </template>
      </el-table-column>
      <el-table-column label="附件标题" align="center" prop="attachmentTitle" />
      <el-table-column label="附件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="operator" />
    </el-table>
  </div>

  <div v-if="payList.length > 0">
    <el-divider style="font-size: 16px; font-weight: bold;">收款信息</el-divider>
    <el-table :summary-method="getPaySummary" show-summary border :data="payList">
      <el-table-column label="付款公司" align="center" prop="company" />
      <el-table-column label="合同签订金额" align="center" width="120" show-overflow-tooltip prop="totalAmount" />
      <el-table-column label="结算金额" align="center" width="120" show-overflow-tooltip prop="settlementAmount" />
      <!-- <el-table-column label="付款百分比" align="center" prop="percentage" /> -->
      <!-- <el-table-column label="金额" align="center" prop="amount" /> -->
      <!-- <el-table-column label="附件" align="center" prop="files" /> -->
      <el-table-column label="备注" width="220" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="发票编号" align="center" width="220" show-overflow-tooltip prop="payNo" />
      <el-table-column label="财务实收金额" align="center" width="120" show-overflow-tooltip prop="receivedAmount" />
      <el-table-column label="收到期票/承兑/保函" align="center" width="120" show-overflow-tooltip prop="promissoryNote" />
      <el-table-column label="期票/承兑/保函到期时间" align="center" prop="promissoryEndDate" />
      <el-table-column label="财务实收百分比(%)" align="center" prop="receivedPercentage" />
      <el-table-column label="附件" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作员" align="center" prop="operator" /> -->
      <!-- <el-table-column label="操作时间" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
          </template>
        </el-table-column> -->
    </el-table>
  </div>


  <div v-if="implementList.length > 0">
    <el-divider style="font-size: 16px; font-weight: bold;">实施日志信息</el-divider>
    <el-table border :data="implementList">
      <el-table-column label="实施日期" align="center" prop="implementDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.implementDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件照片" align="center" prop="images" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.images"  v-if="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="remark" />
      <el-table-column label="文件类型" align="center" prop="fileType">
        <template #default="scope">
          <dict-tag :options="log_type" :value="scope.row.fileType" />
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>

    </el-table>
  </div>


  <div v-if="accountingList.length > 0 && isSales">
    <el-divider style="font-size: 16px; font-weight: bold;">项目核算信息</el-divider>
    <el-table :summary-method="getSummary" show-summary border :data="accountingList">
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="profit_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="此类型的结算总额" align="center" width="100" prop="projectAmount" />
      <el-table-column label="项目税额" align="center" width="100" prop="taxAmount" />
      <el-table-column label="项目材料成本" align="center" width="100" prop="materialCost" />
      <el-table-column label="其他成本一(报销费用)" align="center" width="100" prop="costOne" />
      <el-table-column label="其他成本二" align="center" width="100" prop="costTwo" />
      <el-table-column label="其他成本三" align="center" width="100" prop="costThree" />
      <el-table-column label="资金成本" align="center" width="100" prop="fundCost" />
      <el-table-column label="外协人工成本" align="center" width="100" prop="laborCost" />
      <el-table-column label="税率(%)" align="center" prop="rate" />
      <el-table-column label="毛利润" align="center" width="100" prop="profit" />
      <el-table-column label="成本税费" align="center" width="100" prop="costFees" />
      <el-table-column label="差额税费" align="center" width="100" prop="differenceFees" />
      <el-table-column label="税前利润" align="center" width="100" prop="beforeProfit" />
      <el-table-column label="质保金" align="center" width="100" prop="retentionMoney" />
      <el-table-column label="纯利润扣质保金" align="center" width="100" prop="afterProfit" />
      <el-table-column label="项目提成" align="center" width="100" prop="projectCommission" />
      <el-table-column label="操作员" align="center" prop="operator" />
    </el-table>
  </div>



  <div v-if="warrantyList.length > 0">
    <el-divider style="font-size: 16px; font-weight: bold;">项目质保信息</el-divider>
    <el-table border :data="warrantyList">
      <el-table-column label="付款单位" align="center" prop="company" />
      <el-table-column label="结算金额" align="center" prop="settlementAmount" />
      <!-- <el-table-column label="质保金比例(%)" align="center" prop="warrantyPercentage" /> -->
      <el-table-column label="质保金" align="center" prop="warranty" />
      <el-table-column label="税率(%)" align="center" prop="rate">
        <template #default="scope">
          <dict-tag :options="warranty_rate" :value="scope.row.rate" />
        </template>
      </el-table-column>
      <el-table-column label="周期(月)" align="center" prop="cycle" />
      <el-table-column label="起始日期" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="截止日期" align="center" prop="endDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质保到期剩余(天)" align="center" prop="warrantyRemaining" />
      <el-table-column label="质保金实收金额" align="center" prop="receivedAmount" />
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="文件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
        <template #default="scope">
          <div v-if="scope.row.files">
            <el-link v-for="(file, index) in scope.row.fileName.split(',')" :key="index" type="primary"
              @click="downloadFileW(scope.row, index, file)" style="display: block; margin-bottom: 5px;">
              {{ file }}
            </el-link>
          </div>
          <div v-else>
            <!-- 无文件 -->
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

 <allocation v-if="viewAllocation && userStore.name == 'wuzg'" ref="allocationRef"></allocation>

</template>


<script setup name="ProjectView">
import { onMounted, toRefs } from 'vue';
import {getProject} from "@/api/project/project";
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const allocationRef = ref()
const openAllocation = ref(false)
import allocation from "./allocation.vue";

const props = defineProps({
  datas: {
    type: Object, // 指定类型为对象
    required: true, // 是否必填
  },
  column: {
    type: Number, // 指定类型为数字
    default: 3, // 设置默认值为 3
  },
  sizes: {
    default: 'default',
  },
  personList: {
    default: [],
  },
  payList: {
    default: [],
  },
  attachmentList: {
    default: [],
  },
  implementList: {
    default: [],
  },
  warrantyList: {
    default: [],
  },
  accountingList: {
    default: [],
  },


  isView: {
    default: false,
  },


});
import {getPermission} from "@/api/project/project";
import { ref } from 'vue';

const { datas, column, sizes, personList, payList, attachmentList, implementList, accountingList, warrantyList, isView } = toRefs(props);

const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px',
  }
  return {
    marginRight: marginMap[sizes.value] || marginMap.default,
  }
})
const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { log_type } = proxy.useDict('log_type');
const { profit_type } = proxy.useDict('profit_type');
const { warranty_rate } = proxy.useDict('warranty_rate');

const projectList = ref([]);
const companyList = ref([]);
const open = ref(false);
const openPhase = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const phasetList = ref([]);
const completeObj = ref();
let currentPhase = reactive({
  phaseCode: '',
});
const logs = ref([]);
const data = reactive({
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  amountInfo: {
    should: null,
    actual: null,
    remaining: null,
    gjpShould: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperProject: [],
    phaseCode: null,
  },
  rules: {},

});
async function downloadFile(row) {
  //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
  if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
    let params = {
      projectNo: row.projectNo,
      postIds: [2, 5,6,7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    const res = await getPermission(params).then((response) => {
      console.log("下载附件", response.data);
      return response.data
    });
    if (!res) {
      proxy.$modal.msgError("暂无权限下载此附件");
      return
    }
  }

  var name = row.fileName;
  var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
  a.click()
}

function getSummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'projectAmount',
      'taxAmount',
      'materialCost',
      'costOne',
      'costTwo',
      'costThree',
      'fundCost',
      'laborCost',
      'profit',
      'costFees',
      'differenceFees',
      'beforeProfit',
      'retentionMoney',
      'afterProfit',
      'projectCommission'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}


function getPaySummary(param) {
  const { columns, data } = param;

  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    const key = column.property;
    const validKeys = [
      'receivedAmount',
      'receivedPercentage',
      'promissoryNote'
    ];

    if (!validKeys.includes(key)) {
      sums[index] = '';
      return;
    }

    const sum = data.reduce((acc, item) => {
      return acc + (Number(item[key]) || 0);
    }, 0);

    sums[index] = sum.toFixed(2);
  });

  return sums;
}



function downloadFileW(row, index, name) {
  // var name = row.fileName;
  // var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  let fileArr = row.files.split(',')
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + fileArr[index])
  a.click()
}

const { queryParams, form, rules, amountInfo } = toRefs(data);


const isSales = ref(false)

async function isSale() {
  let params = {
    projectNo: datas.value.projectNo,
    postIds: [5]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  isSales.value = res
}

const viewAllocation = ref(false)



onMounted(async () => {
  await isSale(); // 等待权限检查
  if (datas.value.phaseId >= 6 && userStore.name == 'wuzg') {
    viewAllocation.value = true; // 触发渲染
    await nextTick(); // 等待 DOM 更新
    if (allocationRef.value) {
      allocationRef.value.initData(datas.value, "2", 'accountingComplete');
    }
  }
});


</script>
